$(function () {

    //执行滑动验证码方法
    verifyFn('270','135','270',function (gapLeft,moveLeft) {
        $("[name='gapLeft']").val(gapLeft);
        $("[name='moveLeft']").val(moveLeft);
    });

    //下拉 select 选择标签
    var config = {
        '.chosen-select': {
            max_selected_options: 4//限制选项个数
        },
        '.chosen-select-deselect': {
            allow_single_deselect: true
        },
        '.chosen-select-no-single': {
            disable_search_threshold: 10
        },
        '.chosen-select-no-results': {
            no_results_text: '额... 没有发现!'
        },
        '.chosen-select-width': {
            width: "95%"
        }
    }
    for (var selector in config) {
        $(selector).chosen(config[selector]);
    }

    /**
     * 初始化图片上传
     */
    uploadImgFile({
        selectObj:'#qa-image-upload-box',
        imgNum:4,
        param:'qaImg',
        previewCallback:function (file,src) {//图片选择后预览回调
            var context = '<li><aside class="qu-picture-remove" data-id="'+file.id+'"><a title="删除" class="fs16 c-ccc" href="javascript:void(0);"><i class="fa fa-close"></i></a></aside>';
            context+='<img style="height: 80px;width: 145px;" class="img-rounded" src="'+src+'"></li>';
            $(".question-upload-picture").append(context);
            $("#def-question-img").parent().remove();
        },
        uploadFinished:function (urlList) {//上传完成回调
            if(urlList.length >0){
                var _imageStr = $("#imageStr").val();
                $.each(urlList,function (i, e) {
                    if(_imageStr == ''){
                        _imageStr += e;
                    }else {
                        _imageStr += ',' + e;
                    }
                });
                $("#imageStr").val(_imageStr);
            }
            saveQaData();
        }
    });

    //查询套餐，查询课程列表
    $("body").on("change","#select2",function () {
        $("#select3").find("option").remove();
        $("#select4").find("option").remove();
        var packageId = $("#select2").val();
        $("#select3").append('<option value="0" hassubinfo="false">请选择问题所属课程...</option>');
        queryCourse(packageId);
    }).on("change","#select3",function () {//选择课程，查询章节列表
        $("#select4").empty();
        var courseId = $(this).val();
        if(courseId == 0){
            $("#select4").find("option").remove();
            $('#select4').trigger('chosen:updated');
        }
        $("#select4").append('<option value="0" hassubinfo="false">请选择问题所属章节...</option>');
        queryCatalog(courseId);
    }).on("click","#toggle-code",function () {//切换验证码
        var url =  $("img.v-code-pic").attr('src');
        var _url = url.split("?");
        $("img.v-code-pic").attr('src',_url[0] + '?rnd=' + Math.random());
    }).on('click',".qu-picture-remove",function () {//删除图片
        var _this = $(this);
        var fileId = _this.data("id");
        deleteFile(fileId,function () {
            _this.parent().remove();
            var lis = $(".question-upload-picture>li");
            if(lis.length<=0){
                var context = '<li><img style="width: 145px;height: 80px;" id="def-question-img" src="'+staticPath+'/front/web/v3/img/default/default-course.gif" class="img-rounded"></li>';
                $(".question-upload-picture").html(context);
            }
        });
    }).on("click","#submit",function () {//提交问题表单
        var files = uploader.getFiles();
        if(files!=null && files.length>0){
            uploader.upload();
        }else{
            saveQaData();
        }
    }).on('keyup','textarea[name="context"]',function(){
        var that =$(this);
        if(that.val().replace(/\s/g,"").length>200){
            var blankSize =that.val().length-that.val().replace(/\s/g,"").length;
            that.val( that.val().substring(0,200+blankSize));
            icModale(0,'',"最多可输入200个字");
        }
    });

    /**
     * 选择套餐后，去查询套餐下的课程列表
     * @param packageId 套餐ID
     */
    function queryCourse(packageId){
        if(packageId != null){
            $.ajax({
                url: baseloaction + "/web/qa/getCourseByPackageId",
                data:{"packageId": packageId},
                type:"post",
                dataType:"json",
                async: false,
                success:function (result) {
                    if(result.success){
                        var courseList = result.entity;
                        if(!$.isEmptyObject(courseList)){
                            $.each(courseList,function (index, element) {
                                var option = document.createElement('option');
                                if(element) {
                                    option.value = element.id;
                                    option.innerHTML = element.courseName;
                                    $("#select3").append(option);
                                }
                            });
                        }
                        $('.chosen-select').trigger('chosen:updated');
                    }else {
                        icModale(0,"",result.message);
                    }
                },
                error:function (error) {
                    icModale(0,"","系统繁忙，请稍后重试");
                }
            });
        }
    }

    /**
     * 根据课程ID查询章节列表
     * @param courseId 章节列表
     */
    function queryCatalog(courseId) {
        if(courseId != null && courseId!=0){
            $.ajax({
                url: baseloaction + "/web/qa/getCourseCatalogByCourseId",
                data:{"courseId": courseId},
                type:"post",
                dataType:"json",
                async: false,
                success:function (result) {
                    if(result.success){
                        var courseCatalogList = result.entity;
                        if(!$.isEmptyObject(courseCatalogList)){
                            $.each(courseCatalogList,function (index, element) {
                                var option = document.createElement('option');
                                option.value = element.id;
                                option.innerHTML = element.catalogName;
                                $("#select4").append(option);
                                var childCourseCatalogList = element.childCourseCatalogList;
                                if(!$.isEmptyObject(childCourseCatalogList) && childCourseCatalogList.length > 0){
                                    $.each(childCourseCatalogList, function (i, e) {
                                        var _option = document.createElement('option');
                                        _option.value = e.id;
                                        _option.innerHTML = '&nbsp;&nbsp;'+e.catalogName;
                                        $('#select4').append(_option);
                                    })
                                }
                            });
                        }
                        $('.chosen-select').trigger('chosen:updated');
                    }else {
                        icModale(0,"",result.message);
                    }
                },
                error:function (error) {
                    icModale(0,"","系统繁忙，请稍后重试");
                }
            });
        }
    }
    /**
     * 保存问题
     * @type {boolean}
     */
    function putAjaxQaData(){
        if(flag){
            flag = false;
            var params = $("#questionForm").serializeJSON();

            if(params.privacy==null||params.privacy==undefined){
               params.privacy=1;
            }
            var tagIdList = params.tagIds;
            if(tagIdList){
                var tagIds = '';
                $.each(tagIdList, function (i, e) {
                    tagIds += e + ',';
                })
                tagIds = tagIds.substring(0, tagIds.length-1);
                params.tagIds = tagIds;
            }
            if(params.gapLeft !=null && $.trim(params.gapLeft) !=''){
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(publicKey);
                params.gapLeft = encrypt.encrypt(params.gapLeft);
            }
            if(params.moveLeft !=null && $.trim(params.moveLeft) !=''){
                var encrypt = new JSEncrypt();
                encrypt.setPublicKey(publicKey);
                params.moveLeft = encrypt.encrypt(params.moveLeft);
            }
            params = JSON.stringify(params);
            $.ajax({
                url: baseloaction + '/web/uc/qa/saveQuestion?sign='+sign,
                data: params,
                type: 'post',
                dataType: 'json',
                contentType: 'application/json;charset=utf-8',
                success: function (result) {
                    if(result.success){
                        var question = result.entity;
                        if(question.isFree !=2){//免费
                            window.location.href = baseloaction + '/web/qa/questionInfo?questionId='+question.id;
                        }else {
                            window.location.href = baseloaction +'/web/uc/order/initPayOrder?orderType=COMMON&shopData='+question.id+'-QA-1&shareKey=';
                        }
                    }else {
                        icModale(0,'',result.message);
                        flag = true;
                        sign = result.keyMap.sign;
                        publicKey = result.keyMap.publicKey;
                    }
                },
                error: function (error) {
                    icModale(0,'','系统繁忙，请稍后重试');
                    flag = true;
                }
            })
        }
    }
    /**
     * 保存问题
     * @type {boolean}
     */
    var flag = true
    function saveQaData() {
        var context = $('textarea[name="context"]').val();
        if(context==null || $.trim(context)==''){
            flag =true;
            icModale(0,"","请输入问答内容");
            return false;
        }
        var typeId = $("select[name=typeId]").val();
        if(typeId==null || typeId <=0){
            flag =true;
            icModale(0,"","请选择问答类型");
            return false;
        }
        if(context.replace(/\s/g,"").length>200){
            flag = true;
            icModale(0,"","最多可输入200个字");
            return false;
        }
        var  isFree  = $('input[name="isFree"]').val();
        if(isFree=="2"){
            var  content='本次向'+teacherName+'提问，需支付'+questionFee+'元，<br/>确认支付吗';
            if(questionFee<=0){
                content = '本次向'+teacherName+'提问，本次免费，确认提交问题,<br/>前往本次提问详情';
            }
            layer.open({
                type: 1,
                title: '提示',
                content:content,
                btn: [' 确 定 ', ' 取 消 '],
                area: 'auto',
                btnAlign: 'c',
                shade: [0.3, '#000000'],
                skin: 'lay_ppComment__wrap',
                yes: function (index) {
                    putAjaxQaData();
                    layer.close(index);
                },
                btn2: function (index) {
                    layer.close(index);
                }
            });
        }else{
            putAjaxQaData();
        }
    }
});